package fr.tocchisu.grepolis.services;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import fr.tocchisu.grepolis.model.SendUnit;
import fr.tocchisu.grepolis.model.Town;
import fr.tocchisu.grepolis.model.Unit;
import fr.tocchisu.grepolis.requests.SupportRequest;

public class SupportService extends AbstractService {

	public static void main(String... args) throws ParseException {
		Town town = findTown(readLine("Town : "));
		Date targetDate = new SimpleDateFormat("dd/MM/yy hh:mm:ss").parse(readLine("Target date (dd/MM/yy hh:mm:ss) : "));
		int targetedTown = Integer.valueOf(readLine("Target town id: "));
		List<SendUnit> attackUnitList = new ArrayList<SendUnit>();
		for (Unit unit : Unit.values()) {
			int nbUnits = 0;
			try {
				String readLine = readLine(unit.name().toLowerCase() + ": ");
				if ("".equals(readLine)) {

				}
				nbUnits = Integer.parseInt(readLine);
			} catch (NumberFormatException e) {
			}
			attackUnitList.add(new SendUnit(nbUnits, unit));
		}
		SupportRequest supportRequest = new SupportRequest(town, targetedTown, attackUnitList.toArray(new SendUnit[attackUnitList.size()]));
		ScheduledExecutorService thread = Executors.newSingleThreadScheduledExecutor();
		long delay = targetDate.getTime() - new Date().getTime();
		thread.schedule(supportRequest, delay, TimeUnit.MILLISECONDS);
	}

	private static Town findTown(String townAsString) {
		for (Town town : TOWNS) {
			if (town.getName().equalsIgnoreCase(townAsString)) {
				return town;
			}
		}
		throw new IllegalArgumentException("Town not found");
	}
}
